<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/


if (!is_registered ()) exit;

$id = intval ($_POST['id']);

if ($_POST['value'] == 0) $bad = true;
if ($_POST['value'] == 1) $good = true;

$get_com = $db->query ("SELECT com_rating, com_voters, com_author FROM ".DB_PEREFIX."_comments WHERE com_id = '$id'");
if ($db->num_rows ($get_com) == 1) {
	$com = $db->fetch_array ($get_com);
	
	$vote = false;
	$voters = explode (',', $com['com_voters']);
	foreach ($voters as $v) {
		if (User::$properties['user_id'] == trim($v)) $vote = true;
	}
	
	if ($com['com_voters'] == '')
		$new_voters = User::$properties['user_id'];
	else
		$new_voters = $com['com_voters'].','.User::$properties['user_id'];
	
	$rating = (int) $com['com_rating'];
	
	$unit = 1;

	if (is_admin())
		$unit = 3;
	elseif (my_karma () > 80)
		$unit = 7;
	elseif (my_karma () > 50)
		$unit = 5;
	elseif (my_karma () > 20)
		$unit = 3;
	elseif (my_karma () > 10)
		$unit = 2;
	
	if ($vote == false) {
		if ($bad == true) $rating -= $unit;
		if ($good == true) $rating += $unit;
		
		$db->query ("UPDATE ".DB_PEREFIX."_comments SET com_rating = '$rating', com_voters = '$new_voters' WHERE com_id = '$id'");
		
		if (intval ($com['com_author']) > 0) {
			$get_author = $db->query ("SELECT user_karma FROM ".DB_PEREFIX."_users WHERE user_id = ".$com['com_author']);
			$author = $db->fetch_array ($get_author);
			$author_karma = $author['user_karma'];
			$author_karma = ($good) ? $author_karma + "0.5" : $author_karma - "0.5";
			$db->query ("UPDATE ".DB_PEREFIX."_users SET user_karma = '$author_karma' WHERE user_id = ".$com['com_author']);
		}
	}

	($rating == 0) ? $rating = "<span class=\"com_rating_zero\">0</span>" : ($rating > 0) ? $rating = "<span class=\"com_rating_plus\">+{$rating}</span>" : $rating = "<span class=\"com_rating_minus\">$rating</span>";
	print $rating;
	
	Templater::load ('comment.tpl');	
	print Templater::display_part ('cant_rating');
}

